package com.wzxl.utils.misc;

import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author rxbyes
 * @version V1.0
 * @package com.wzxl.utils
 * @description: TODO (流水号生成规则)
 * @date 2017-11-下午6:30
 */

public class PrimaryGenerater {

    private static PrimaryGenerater primaryGenerater;

    private static final String SERIALNUMBER = "6201";

    private static final String EXPECT_NUMBER = "number";

    public static final String LAKH = "000000";

    public static final String LAKH_ONE = "000001";

    private static final String YY_MM_DD = "yyMMdd";

    /**
     * 防止重建对象
     */
    private PrimaryGenerater() {

    }

    private SimpleDateFormat format(String var1) {
        return new SimpleDateFormat(var1);
    }

    /**
     * 获取单实例对象
     *
     * @return
     */
    public static PrimaryGenerater getInstance() {
        if (null == primaryGenerater) {
            synchronized (PrimaryGenerater.class) {
                if (null == primaryGenerater) {
                    primaryGenerater = new PrimaryGenerater();
                }
            }
        }
        return primaryGenerater;
    }

    private Map<String, String> maps = new ConcurrentHashMap<>(16);

    public synchronized Map<String, String> getSerialNumber() {
        String serialNumber = null;
        if (StringUtils.isEmpty(maps.get(EXPECT_NUMBER))) {
            serialNumber = SERIALNUMBER.concat(this.format(YY_MM_DD).format(new Date()).concat(LAKH_ONE));
        } else {
            serialNumber = setUniqNumber(maps.get(EXPECT_NUMBER));
        }
        maps.put(EXPECT_NUMBER, serialNumber);
        return maps;
    }

    @NotNull
    private String setUniqNumber(String number) {
        DecimalFormat df = new DecimalFormat(LAKH);
        return SERIALNUMBER
                .concat(this.format(YY_MM_DD).format(new Date()))
                .concat(df.format(1 + Integer.parseInt(number.substring(10, 16))));
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public String getNumbers() {
        return maps.get(EXPECT_NUMBER);
    }

    public String add(String var1) {
        if (StringUtils.isEmpty(var1)) {
            throw new NullPointerException(" request parameter number is not null");
        }
        String number = setUniqNumber(var1);
        maps.put(EXPECT_NUMBER, setUniqNumber(var1));
        return number;
    }
}
